Page({
  data: {
    merchantInfo: {},
    todayOrders: 0,
    todayIncome: 0,
    menuList: [],
    activeTab: "menu", // 当前激活的标签页：menu-菜单管理，orders-订单管理，reviews-评价管理
  },

  onLoad() {
    // 检查登录状态
    const merchantInfo = wx.getStorageSync("merchantInfo");
    if (!merchantInfo) {
      wx.redirectTo({
        url: "/pages/login/login?type=merchant",
      });
      return;
    }

    this.setData({ merchantInfo });

    // 获取今日数据
    this.getTodayStats();
    // 获取菜单列表
    this.getMenuList();
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });

    // 加载对应标签页的数据
    switch (tab) {
      case "orders":
        this.getOrderList();
        break;
      case "reviews":
        this.getReviewList();
        break;
    }
  },

  // 获取今日数据
  getTodayStats() {
    // 使用模拟数据
    this.setData({
      todayOrders: 126,
      todayIncome: 1358.0,
    });
  },

  // 获取菜单列表
  getMenuList() {
    // 使用模拟数据
    const menuList = [
      {
        _id: 1,
        name: "红烧肉饭",
        price: 12.0,
        description: "精选五花肉，配以土豆胡萝卜，搭配时令青菜",
        image: "/images/dishes/hongshaorou.jpg",
        nutritionInfo: {
          calories: 650,
          protein: "25g",
          carbs: "80g",
          fat: "22g",
        },
      },
      {
        _id: 2,
        name: "宫保鸡丁饭",
        price: 10.0,
        description: "鸡肉丁炒花生，配以胡萝卜青椒，口感香脆",
        image: "/images/dishes/gongbaojiding.jpg",
        nutritionInfo: {
          calories: 580,
          protein: "28g",
          carbs: "75g",
          fat: "18g",
        },
      },
      {
        _id: 3,
        name: "番茄炒蛋饭",
        price: 8.0,
        description: "新鲜番茄配农家土鸡蛋，搭配时令青菜",
        image: "/images/dishes/fanqiechaodan.jpg",
        nutritionInfo: {
          calories: 450,
          protein: "18g",
          carbs: "65g",
          fat: "15g",
        },
      },
    ];
    this.setData({ menuList });
  },

  // 获取订单列表
  getOrderList() {
    // 模拟订单数据
    const orderList = [
      {
        _id: 1,
        orderNo: "202403150001",
        status: "待接单",
        items: [
          { name: "红烧肉饭", quantity: 1, price: 12.0 },
          { name: "宫保鸡丁饭", quantity: 2, price: 20.0 },
        ],
        totalAmount: 32.0,
        createTime: "2024-03-15 12:30:45",
        remark: "不要辣",
      },
      {
        _id: 2,
        orderNo: "202403150002",
        status: "制作中",
        items: [{ name: "番茄炒蛋饭", quantity: 1, price: 8.0 }],
        totalAmount: 8.0,
        createTime: "2024-03-15 12:35:22",
        remark: "",
      },
    ];
    this.setData({ orderList });
  },

  // 获取评价列表
  getReviewList() {
    // 模拟评价数据
    const reviewList = [
      {
        _id: 1,
        userName: "张**",
        avatar: "/images/default_avatar.png",
        rating: 5,
        content: "红烧肉很入味，米饭也很香！",
        createTime: "2024-03-15 13:45:00",
        reply: "",
      },
      {
        _id: 2,
        userName: "李**",
        avatar: "/images/default_avatar.png",
        rating: 4,
        content: "味道不错，就是等待时间有点长",
        createTime: "2024-03-15 12:30:00",
        reply: "感谢您的反馈，我们会继续改进服务质量",
      },
    ];
    this.setData({ reviewList });
  },

  // 添加菜品
  handleAddDish() {
    wx.navigateTo({
      url: "/pages/merchant/dish/add",
    });
  },

  // 编辑菜品
  handleEditDish(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/merchant/dish/edit?id=${id}`,
    });
  },

  // 删除菜品
  handleDeleteDish(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "确认删除",
      content: "确定要删除这个菜品吗？",
      success: (res) => {
        if (res.confirm) {
          // 从列表中移除
          const menuList = this.data.menuList.filter((item) => item._id !== id);
          this.setData({ menuList });

          wx.showToast({
            title: "删除成功",
            icon: "success",
          });
        }
      },
    });
  },

  // 处理订单
  handleOrder(e) {
    const { id, action } = e.currentTarget.dataset;
    const actionText = {
      accept: "接单",
      reject: "拒单",
      complete: "完成",
    }[action];

    wx.showModal({
      title: `确认${actionText}`,
      content: `确定要${actionText}这个订单吗？`,
      success: (res) => {
        if (res.confirm) {
          // 更新订单状态
          const orderList = this.data.orderList.map((order) => {
            if (order._id === id) {
              switch (action) {
                case "accept":
                  order.status = "制作中";
                  break;
                case "reject":
                  order.status = "已拒单";
                  break;
                case "complete":
                  order.status = "已完成";
                  break;
              }
            }
            return order;
          });
          this.setData({ orderList });

          wx.showToast({
            title: `${actionText}成功`,
            icon: "success",
          });
        }
      },
    });
  },

  // 回复评价
  handleReplyReview(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "回复评价",
      editable: true,
      placeholderText: "请输入回复内容",
      success: (res) => {
        if (res.confirm && res.content) {
          // 更新评价回复
          const reviewList = this.data.reviewList.map((review) => {
            if (review._id === id) {
              review.reply = res.content;
            }
            return review;
          });
          this.setData({ reviewList });

          wx.showToast({
            title: "回复成功",
            icon: "success",
          });
        }
      },
    });
  },

  // 导出订单数据
  handleExportOrders() {
    wx.showLoading({ title: "正在导出..." });
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: "导出成功",
        icon: "success",
      });
    }, 1500);
  },

  // 编辑商家信息
  handleEditInfo() {
    wx.navigateTo({
      url: "/pages/merchant/info/edit",
    });
  },

  // 退出登录
  handleLogout() {
    wx.showModal({
      title: "确认退出",
      content: "确定要退出登录吗？",
      success: (res) => {
        if (res.confirm) {
          // 清除登录信息
          wx.removeStorageSync("merchantInfo");
          wx.removeStorageSync("merchantToken");

          // 跳转到登录页
          wx.redirectTo({
            url: "/pages/login/login?type=merchant",
          });
        }
      },
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.getTodayStats();

    switch (this.data.activeTab) {
      case "menu":
        this.getMenuList();
        break;
      case "orders":
        this.getOrderList();
        break;
      case "reviews":
        this.getReviewList();
        break;
    }

    wx.stopPullDownRefresh();
  },
});
